﻿// 麻省理工学院许可证
//
// 版权所有 (c) 2023-2025 缄默 联系电话/18521355630 
//
// 特此免费授予获得本软件的任何人以处理本软件的权利，但须遵守以下条件：在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
//
// 软件按“原样”提供，不提供任何形式的明示或暗示的保证，包括但不限于对适销性、适用性和非侵权的保证。
// 在任何情况下，作者或版权持有人均不对任何索赔、损害或其他责任负责，无论是因合同、侵权或其他方式引起的，与软件或其使用或其他交易有关。

using Infragistics.Win;
using Infragistics.Win.UltraWinToolbars;

namespace LvcChong
{
    public partial class Pagination : UserControl
    {
        private bool isInitialize = false;

        #region 属性

        /// <summary>
        /// 当页码改变时会触发
        /// </summary>
        public event EventHandler OnPageChanged;

        public event EventHandler OnPageSizeChanged;

        private int _pageSize = 50;

        /// <summary>
        /// 页大小
        /// </summary>
        public int PageSize
        {
            get { return _pageSize; }
            set
            {
                if (value <= 0)
                    _pageSize = 20;
                //else if (value == 0)
                //    _pageSize = _totalRecords;
                else
                    _pageSize = value;

                (ultraToolbarsManager1.Tools["cboPageSize"] as ComboBoxTool).Text = _pageSize.ToString();

                OnPageSizeChanged?.Invoke(this, null);
                // 初始化
                if (_pageSize == 0)
                    TotalPages = 1;
                else
                    TotalPages = Convert.ToInt32(Math.Ceiling((decimal)_totalRecords / _pageSize));
            }
        }

        private int _currentPageNo = 1;

        /// <summary>
        /// 当前页号
        /// </summary>
        public int CurrentPageNo
        {
            get { return _currentPageNo; }
            set
            {
                var tempPageNo = 1;
                if (value <= 0)
                    tempPageNo = 1;
                else if (value > TotalPages)
                    tempPageNo = TotalPages;
                else
                    tempPageNo = value;

                if (!isInitialize)
                    OnPageChanged?.Invoke(this, null);

                _currentPageNo = tempPageNo;
                // 刷新显示
                ultraToolbarsManager1.Tools["lblCurrPage"].SharedProps.Caption = $"当前第 {_currentPageNo}/{_totalPages} 页   共 {_totalRecords} 条";
            }
        }

        private int _totalPages = 1;

        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPages
        {
            get { return _totalPages; }
            private set
            {
                if (value <= 0)
                    _totalPages = 1;
                else
                    _totalPages = value;

                // 改变总页数则当前页默认返回到第一页
                CurrentPageNo = 1;
            }
        }

        private long _totalRecords = 0;

        /// <summary>
        /// 总记录数
        /// </summary>
        public long TotalRecords
        {
            get { return _totalRecords; }
            private set
            {
                if (_totalRecords == value) return;

                _totalRecords = value;

                // 初始化
                if (PageSize == 0)
                    TotalPages = 1;
                else
                    TotalPages = Convert.ToInt32(Math.Ceiling((decimal)_totalRecords / _pageSize));
            }
        }

        #endregion 属性

        public Pagination()
        {
            InitializeComponent();

            var cbo = ultraToolbarsManager1.Tools["cboPageSize"] as ComboBoxTool;
            cbo.ValueList.ValueListItems.Clear();
            cbo.ValueList.ValueListItems.Add(10, "10");
            cbo.ValueList.ValueListItems.Add(20, "20");
            cbo.ValueList.ValueListItems.Add(50, "50");
            cbo.ValueList.ValueListItems.Add(100, "100");
        }

        /// <summary>
        /// 初始化分页数据信息
        /// </summary>
        /// <param name="totalRecords">总记录数</param>
        /// <param name="pageNo">当前页</param>
        /// <param name="pageSize">页大小</param>
        [Obsolete("此方法已经弃用，请使用 RefreshPageData 方法替代")]
        public void BindPageInfo(long totalRecords, int pageNo = 1, int pageSize = 20)
        {
            if (totalRecords < 0) throw new ArgumentException("记录数必须是大于0的整数");

            isInitialize = true;
            this.TotalRecords = totalRecords;

            (ultraToolbarsManager1.Tools["cboPageSize"] as ComboBoxTool).Value = pageSize;

            this.CurrentPageNo = pageNo;

            ResetButtonEnable();
            isInitialize = false;
        }

        public void RefreshPageData(long totalRecords)
        {
            if (totalRecords < 0) throw new ArgumentException("记录数必须是大于0的整数");

            isInitialize = true;
            this.TotalRecords = totalRecords;
            ResetButtonEnable();
            isInitialize = false;
        }

        private void ultraToolbarsManager1_ToolClick(object sender, ToolClickEventArgs e)
        {
            switch (e.Tool.Key)
            {
                // 首页
                case "btnFirst":
                    CurrentPageNo = 1;
                    break;
                // 上一页
                case "btnPre":
                    CurrentPageNo--;
                    break;
                // 下一页
                case "btnNext":
                    CurrentPageNo++;
                    break;
                // 末页
                case "btnLast":
                    CurrentPageNo = TotalPages;
                    break;
                // 跳转
                case "btnGoPage":
                    if (int.TryParse((ultraToolbarsManager1.Tools["cboPage"] as ComboBoxTool).Text, out int goPage)
                        && !(ultraToolbarsManager1.Tools["cboPage"] as ComboBoxTool).ValueList.ValueListItems.Cast<ValueListItem>().Any(x => x.DataValue.ToString() == (ultraToolbarsManager1.Tools["cboPage"] as ComboBoxTool).Text))
                        (ultraToolbarsManager1.Tools["cboPage"] as ComboBoxTool).ValueList.ValueListItems.Add(
                            new ValueListItem
                            {
                                DisplayText = (ultraToolbarsManager1.Tools["cboPage"] as ComboBoxTool).Text,
                                DataValue = (ultraToolbarsManager1.Tools["cboPage"] as ComboBoxTool).Text,
                            });
                    CurrentPageNo = goPage;
                    break;
            }

            ResetButtonEnable();
        }

        private void ultraToolbarsManager1_ToolKeyPress(object sender, ToolKeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                switch (e.Tool.Key)
                {
                    // 跳转页
                    case "cboPage":
                        int.TryParse((e.Tool as ComboBoxTool).Text, out int pageNo);
                        CurrentPageNo = pageNo;
                        break;
                }

                ResetButtonEnable();
            }
        }

        private void ultraToolbarsManager1_ToolValueChanged(object sender, ToolEventArgs e)
        {
            switch (e.Tool.Key)
            {
                // 页大小
                case "cboPageSize":
                    int.TryParse((e.Tool as ComboBoxTool).Text, out int pageSize);
                    PageSize = pageSize;
                    break;
            }

            ResetButtonEnable();
        }

        /// <summary>
        /// 重置按钮状态
        /// </summary>
        private void ResetButtonEnable()
        {
            ultraToolbarsManager1.Tools["btnFirst"].SharedProps.Enabled = CurrentPageNo != 1;
            ultraToolbarsManager1.Tools["btnPre"].SharedProps.Enabled = CurrentPageNo != 1;
            ultraToolbarsManager1.Tools["btnLast"].SharedProps.Enabled = CurrentPageNo != TotalPages;
            ultraToolbarsManager1.Tools["btnNext"].SharedProps.Enabled = CurrentPageNo != TotalPages;

            ultraToolbarsManager1.Tools["btnGoPage"].SharedProps.Enabled = TotalPages != 1;
            ultraToolbarsManager1.Tools["cboPage"].SharedProps.Enabled = TotalPages != 1;
        }
    }
}